﻿using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using YaAppoint.Appointments.Pools;

namespace YaAppoint.Appointments.Schedules.Pools
{
    /// <summary>
    /// 号池领域服务
    /// </summary>
    public class PoolManager(IRepository<Pool,Guid> poolRepository):DomainService
    {
        private readonly IRepository<Pool, Guid> _poolRepository = poolRepository;

        public async Task UpdateAsync(Pool pool)
        {
            if (pool.Current > pool.MaxCount)
            {
                // 最大预约量不得小于当前已预约数量
                throw new BusinessException(CustomErrorCodes.CurrentCountBiggerThanMaxCount);
            }
            if (pool.EndTime < DateTime.Now)
            {
                // 号池过期
                throw new BusinessException(CustomErrorCodes.PoolExpired);
            }

            await _poolRepository.UpdateAsync(pool);
        }

        public async Task DeleteAsync(Guid id)
        { 
            var pool = await _poolRepository.GetAsync(id);
            if (pool!=null)
            {
                if (pool.Current > 0 || pool.Appointments.Count > 0)
                {
                    throw new BusinessException(CustomErrorCodes.AppointmentAlreadyInPool);
                }
                await _poolRepository.DeleteAsync(pool);
            }
        }
    }
}
